<template>
	<view class="app-tabbar-layout" :style="[AppSkinVar]">
		<block v-for="(item, index) in tabbarDatas[1]" :key="item.tabbarIndex">
			<template v-if="isLoad[item.tabbarIndex]">
				<view class="app-tabbar-layout__body" v-show="tabbarPageIndex === item.tabbarIndex">
					<layout-page :index="`${item.tabbarIndex}`" @endRefresh="stopDownRefresh" :pageData="item" @setPageHeaderColor="setTabbarHeaderColor"></layout-page>
				</view>
			</template>
		</block>
	</view>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { onLoad, onReady,onShow, onHide, onBackPress, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import layoutPage from './child/layout.vue';
import customTabbar from './utils/customTabbar';
import { useTabbarHeader } from './utils/hooks';
import { useInit } from '@/common/stores';
import type { TabbarItem } from '@/common/stores';
import { storeToRefs } from 'pinia';

const props = defineProps<{
	index:string
}>();

const initStore = useInit();

const { tabbarData, tabbarPageIndex } = storeToRefs(initStore);

// 储存tab页是否被打开过一次，模拟load效果
const isLoad = reactive<boolean[]>([]);

const tabbarDatas = computed(() => {
	let arr: [
		Array<
			TabbarItem & {
				tabbarIndex: number;
			}
		>,
		Array<
			TabbarItem & {
				tabbarIndex: number;
			}
		>
	] = [[], []];
	tabbarData.value.forEach((item, index) => {
		if (index > 0) {
			if (item.link?.type == 2) {
				arr[0].push({
					...item,
					tabbarIndex: index
				});
			} else {
				arr[1].push({
					...item,
					tabbarIndex: index
				});
			}
		}
	});
	return arr;
});

const { setTabbarHeaderColor } = useTabbarHeader(Number(props.index));

const init = () => {
	isLoad.splice(0);
	tabbarData.value.forEach((item, index) => {
		isLoad.push(`${index}` === props.index);
	});
};

const stopDownRefresh = () => {
	// 停止下拉动作
	uni.stopPullDownRefresh();
};

watch(tabbarData, () => {
	init();
});

onLoad(() => {
	init();
});
onReady(() => {
	const title = tabbarData.value[Number(props.index)].text;
	uni.setNavigationBarTitle({
		title
	});
});

onShow(() => {
	customTabbar.onShow(props.index);
});
onHide(() => {
	customTabbar.onHide();
});
// 监听页面返回
onBackPress(() => {
	customTabbar.onShow(props.index);
});
onReachBottom(() => {
	customTabbar.onReachBottom(props.index);
});
onPullDownRefresh(() => {
	customTabbar.onPullDownRefresh(props.index);
});

defineExpose({
		propsIndex:props.index
	});
</script>

<style lang="scss">
page {
	background-color: #f7f7f7;
}
@include appBem_b(tabbar-layout) {
	padding-bottom: 50px;
}
</style>
